package com.book.filter;

import com.book.entity.Admin;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.java.Log;

import java.io.IOException;
import java.util.Objects;

/**
 * @Author zzw2000
 * @Date 2022年08月10日 20:03
 * @Description 登录拦截
 */
@WebFilter("/*")
@Log
public class LoginFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        String url = req.getRequestURL().toString();
        if (!url.contains("/static/") && !url.endsWith("login") && !url.endsWith("register")) {
            HttpSession session = req.getSession();
            Admin user = (Admin) session.getAttribute("user");
            if (Objects.isNull(user)) {
                res.sendRedirect("login");
                log.info("访问链接：" + url + "被拦截");
                return;
            }
        }
        log.info("访问链接：" + url + "被放行");
        chain.doFilter(req, res);
    }
}
